﻿using MediatR;
using T.Vehicleservice.Domain.Dtos;
using T.Vehicleservice.Domain.T.Vehicleservice.Model;
using T.Vehicleservice.Read.API.Application.Command.AccidentRecordCommand;
using T.Vehicleservice.Repository.Interface;

namespace T.Vehicleservice.Read.API.Application.CommandHandlers.AccidentRecordCommandHandler
{
    public class AccidentRecordShowCommandHandler : IRequestHandler<AccidentRecordShowCommand, PageDto<AccidentRecord>>
    {
        private readonly IAccidentRecordRepository _accidentRecordRepository;
        public AccidentRecordShowCommandHandler(IAccidentRecordRepository accidentRecordRepository)
        {
            _accidentRecordRepository = accidentRecordRepository;
        }
        public async Task<PageDto<AccidentRecord>> Handle(AccidentRecordShowCommand request, CancellationToken cancellationToken)
        {
            var list = (await _accidentRecordRepository.GetAllAsync()).Where(x => !x.IsDeleted);
            if (!string.IsNullOrEmpty(request.LicensePlateNumber))
            {
                list=list.Where(x=>x.LicensePlateNumber.Contains(request.LicensePlateNumber));
            }
            if (!string.IsNullOrEmpty(request.AccidentTitle))
            {
                list = list.Where(x => x.AccidentTitle.Contains(request.AccidentTitle));
            }
            if (request.AccidentDate != null)
            {
                list=list.Where(x=>x.AccidentDate==Convert.ToDateTime(request.AccidentDate).AddDays(1));
            }
            if (request.CompanyID != null)
            {
                list=list.Where(x=>x.CompanyID==request.CompanyID);
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if(request.PageSize == null)
            {
                request.PageSize = list.Count();
            }
            PageDto<AccidentRecord> page= new PageDto<AccidentRecord>();
            page.TotalCount = list.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list = list.OrderByDescending(o => o.CreatedDate).Skip((int)(request.PageIndex - 1) * (int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
